//
//  FQDCompleteUserInfoViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/10/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import <MobileCoreServices/MobileCoreServices.h>
#import "FQDCompleteUserInfoViewController.h"
#import "FQDAccountInputField.h"
#import "FQDNavigationView.h"
#import "MBProgressHUD+FQDExtension.h"
#import "NSString+FQDValidation.h"
#import "FQDAccountManager.h"
#import "FQDRestModel.h"

#import "Masonry.h"

@interface FQDCompleteUserInfoViewController () <UITextViewDelegate,
                                                 UINavigationControllerDelegate,
                                                 UIImagePickerControllerDelegate>

// 头像按钮
@property (nonatomic, strong) UIButton *avatarButton;
// 昵称输入框
@property (nonatomic, strong) FQDAccountInputField *nameInputField;
// 简介
@property (nonatomic, strong) UITextView *signatureTextView;
// 简介占位文本
@property (nonatomic, strong) UILabel *signaturePlaceHolder;
// 简介描述占位文本
@property (nonatomic, strong) UILabel *signatureDescPlaceHolder;
// 简介输入框分割线
@property (nonatomic, strong) UIView *signatureSeparator;
// 完成按钮
@property (nonatomic, strong) UIButton *finishButton;
// 上传头像图片数据
@property (nonatomic, strong) FQDMultipartFileData *avatarPartFileData;

@end

@implementation FQDCompleteUserInfoViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.hideKeyboardOnTap = YES;
    self.navView.titleLabel.text = @"完善资料";
    
    UIImage *avatarImage = [UIImage imageNamed:@"Avatar"];
    self.avatarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.avatarButton setImage:avatarImage forState:UIControlStateNormal];
    [self.avatarButton addTarget:self action:@selector(editAvatar:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.avatarButton];
    
    WeakSelf;
    [self.avatarButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(90);
        make.centerX.equalTo(weakSelf.view);
        make.size.equalTo(@80);
    }];
    
    self.nameInputField = [[FQDAccountInputField alloc] init];
    [self.nameInputField setPlaceHolderString:@"昵称"];
    [self.view addSubview:self.nameInputField];
    
    [self.nameInputField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.avatarButton.mas_bottom).offset(40);
        make.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@44);
    }];
    
    self.signatureTextView = [[UITextView alloc] init];
    self.signatureTextView.font = FQDRegularFontWithSize(14.0f);
    self.signatureTextView.textColor = [UIColor whiteColor];
    self.signatureTextView.backgroundColor = [UIColor clearColor];
    self.signatureTextView.delegate = self;
    [self.view addSubview:self.signatureTextView];
    
    [self.signatureTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.nameInputField.mas_bottom);
        make.left.equalTo(weakSelf.view).offset(5);
        make.right.equalTo(weakSelf.view);
        make.height.equalTo(@56);
    }];
    
    self.signaturePlaceHolder = [[UILabel alloc] init];
    self.signaturePlaceHolder.font = FQDRegularFontWithSize(14.0f);
    self.signaturePlaceHolder.textColor = [UIColor colorWithWhite:1.0f alpha:0.6f];
    self.signaturePlaceHolder.text = @"简介";
    [self.signaturePlaceHolder sizeToFit];
    [self.signatureTextView addSubview:self.signaturePlaceHolder];
    
    [self.signaturePlaceHolder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.equalTo(weakSelf.signatureTextView).offset(8);
    }];
    
    self.signatureDescPlaceHolder = [[UILabel alloc] init];
    self.signatureDescPlaceHolder.font = FQDRegularFontWithSize(12.0f);
    self.signatureDescPlaceHolder.textColor = [UIColor colorWithWhite:1.0f alpha:0.6f];
    self.signatureDescPlaceHolder.text = @"这个人有好奇心";
    [self.signatureDescPlaceHolder sizeToFit];
    [self.signatureTextView addSubview:self.signatureDescPlaceHolder];
    
    [self.signatureDescPlaceHolder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.signaturePlaceHolder.mas_right);
        make.bottom.equalTo(weakSelf.signaturePlaceHolder);
    }];
    
    self.signatureSeparator = [[UIView alloc] init];
    self.signatureSeparator.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.2f];
    [self.view addSubview:self.signatureSeparator];
    
    [self.signatureSeparator mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.signatureTextView.mas_bottom);
        make.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@0.5);
    }];
    
    UIImage *finishImage = [UIImage imageNamed:@"Okay Button"];
    self.finishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishButton setImage:finishImage forState:UIControlStateNormal];
    [self.finishButton addTarget:self action:@selector(finish:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.finishButton];
    
    [self.finishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.signatureTextView.mas_bottom).offset(40);
        make.centerX.equalTo(weakSelf.view);
        make.size.mas_equalTo(CGSizeMake(163, 44));
    }];
    
}

#pragma mark - Event response
- (void)editAvatar:(id)sender
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil
                                          preferredStyle:UIAlertControllerStyleActionSheet];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIAlertAction *photoLibrary = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * _Nonnull action) {
             UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
             imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
             imagePicker.delegate = self;
             [self presentViewController:imagePicker animated:YES completion:nil];
        }];
        
        [alertController addAction:photoLibrary];
    } else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault
         handler:^(UIAlertAction * _Nonnull action) {
             UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
             imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
             imagePicker.delegate = self;
             [self presentViewController:imagePicker animated:YES completion:nil];
        }];
        
        [alertController addAction:camera];
    }
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)finish:(id)sender
{
    NSString *username = self.nameInputField.textField.text;
    if ([username isBlankString]) {
        [MBProgressHUD showMessage:@"请输入昵称"];
        return;
    }

    NSString *email = self.email;
    NSString *password = self.password;
    NSString *signature = self.signatureTextView.text;
    
    [MBProgressHUD showLoadingAnim];
    [[QDailyAPI sharedAPI] completeRegisterWithEmail:email
     password:password
     username:username
     signature:signature
     avatarPartFileData:self.avatarPartFileData
     completion:^(id responseObject, NSError *error) {
         NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
         if ([status integerValue] == 200) {
             id response = responseObject[@"response"];
             FQDUser *user = [FQDUser yy_modelWithJSON:response];
             [[FQDAccountManager sharedManager] changeCurrentUser:user];
             [self dismissViewControllerAnimated:YES completion:nil];
         }
         [MBProgressHUD hideLoadingAnim];
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5f);
        [self.avatarButton setImage:image forState:UIControlStateNormal];
        
        FQDMultipartFileData *partFileData = [FQDMultipartFileData fileDataWithData:imageData];
        partFileData.fileName = @"avatar.jpg";
        partFileData.mimeType = @"image/jpeg";
        self.avatarPartFileData = partFileData;
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.signaturePlaceHolder.hidden = ([textView.text length] > 0);
    self.signatureDescPlaceHolder.hidden = ([textView.text length] > 0);
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.signaturePlaceHolder.hidden = ([textView.text length] > 0);
    self.signatureDescPlaceHolder.hidden = ([textView.text length] > 0);
    
//    CGSize fitSize = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, MAXFLOAT)];
//    CGFloat maxHeight = MIN(MAX(fitSize.height, 33.0f), 83.0f);
//    if (maxHeight != textView.frame.size.height) {
//        [textView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.equalTo(@(maxHeight));
//        }];
//    }
    
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.signaturePlaceHolder.hidden = ([textView.text length] > 0);
    self.signatureDescPlaceHolder.hidden = ([textView.text length] > 0);
}

@end
